package net.gazhi.delonix.rbac.service;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import net.gazhi.delonix.core.annonation.ApiLevel;
import net.gazhi.delonix.core.jpa.AbstractEntityService;
import net.gazhi.delonix.rbac.entity.Action;
import net.gazhi.delonix.rbac.entity.DX_TABLE;
import net.gazhi.delonix.rbac.entity.LoginUser;

@Service
public class ActionService extends AbstractEntityService<Action> {

	/**
	 * 列出指定 level 的 Action
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Action> list(ApiLevel level) {
		return (List<Action>) createCriteria("act").createAlias("act.controller", "ctr").createAlias("ctr.module", "mdl").add(Restrictions.eq("level", level.value())).addOrder(Order.asc("mdl.id"))
				.addOrder(Order.asc("ctr.id")).addOrder(Order.asc("act.showOrder")).list();
	}

	/**
	 * 查找用户有权限的功能点 ID
	 * 
	 * @param userId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<String> findGrantPaths(LoginUser loginUser) {
		Query query = null;
		do {
			if (loginUser.getIsSuperAdmin()) {
				String sql = "select path from " + DX_TABLE.dx_action;
				query = dao.createSQLQuery(sql);
				break;
			}
			if (loginUser.isGuest()) {
				String sql = "select path from " + DX_TABLE.dx_action + " where level=:PUBLIC";
				query = dao.createSQLQuery(sql).setInteger("level", ApiLevel.PUBLIC.value());
				break;
			}
			String sql = "select path from " + DX_TABLE.dx_action + " where level=:PUBLIC or level=:USER_DEFAULT or level=:GRANT_REQUIRED and id in(select action_id from " + DX_TABLE.dx_role_action
					+ " ra, " + DX_TABLE.dx_user + " u where ra.role_id=u.role_id and u.id=:USER_ID)";
			query = dao.createSQLQuery(sql).setInteger("USER_ID", loginUser.getId());
			query.setInteger("PUBLIC", ApiLevel.PUBLIC.value()).setInteger("USER_DEFAULT", ApiLevel.USER_DEFAULT.value()).setInteger("GRANT_REQUIRED", ApiLevel.GRANT_REQUIRED.value());
		} while (false);
		return query.list();
	}

}
